<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getOrderDetailAPI } from '@/apis/order'
import Cookies from 'js-cookie'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 状态映射配置
const stateMap = {
  '1': { text: '待付款', color: '#e6a23c' },
  '2': { text: '待发货', color: '#409eff' },
  '3': { text: '已发货', color: '#67c23a' },
  '5': { text: '已完成', color: '#909399' },
  '0': { text: '已取消', color: '#909399' }
}

// 订单详情数据
const orderDetail = ref(null)
const loading = ref(false)

// 格式化状态显示
const formatPayState = (status) => {
  return stateMap[status]?.text || '未知状态'
}

// 获取订单详情
const getOrderDetail = async () => {
  try {
    loading.value = true
    const memberId = Cookies.get('memberId')

    if (!memberId) {
      ElMessage.warning('请先登录')
      return router.push('/login')
    }

    const res = await getOrderDetailAPI(route.params.orderNo)

    if (res.code === 200) {
      orderDetail.value = {
        ...res.data,
        // 处理时间格式
        createTime: res.data.createTime
            ? dayjs(res.data.createTime).format('YYYY-MM-DD HH:mm')
            : '--',
        payTime: res.data.payTime
            ? dayjs(res.data.payTime).format('YYYY-MM-DD HH:mm')
            : '--',
        deliverTime: res.data.deliverTime
            ? dayjs(res.data.deliverTime).format('YYYY-MM-DD HH:mm')
            : '--',
        receiveTime: res.data.receiveTime
            ? dayjs(res.data.receiveTime).format('YYYY-MM-DD HH:mm')
            : '--',
        // 处理商品规格
        items: res.data.items.map(item => ({
          ...item,
          attrsText: JSON.parse(item.productAttr).valueName
        }))
      }
    } else {
      ElMessage.error(res.message || '获取订单详情失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => getOrderDetail())
</script>

<template>
  <div class="order-detail-container">
    <!-- 返回按钮 -->
    <el-button type="primary" link @click="router.go(-1)" class="back-btn">
      <i class="el-icon-arrow-left"></i> 返回订单列表
    </el-button>

    <!-- 加载状态 -->
    <el-skeleton :loading="loading" animated :rows="10">
      <template #default>
        <!-- 订单不存在提示 -->
        <el-empty v-if="!orderDetail" description="订单不存在" />

        <!-- 订单详情内容 -->
        <div v-else class="detail-content">
          <!-- 基础信息 -->
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>订单信息</span>
              </div>
            </template>

            <el-descriptions :column="2" border>
              <el-descriptions-item label="订单编号">{{ orderDetail.orderNo }}</el-descriptions-item>
              <el-descriptions-item label="订单状态">
                <el-tag :color="stateMap[orderDetail.statusName]?.color">
                  {{ formatPayState(orderDetail.statusName) }}
                </el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="下单时间">{{ orderDetail.createTime }}</el-descriptions-item>
              <el-descriptions-item label="支付时间">{{ orderDetail.payTime }}</el-descriptions-item>
              <el-descriptions-item label="发货时间">{{ orderDetail.deliverTime }}</el-descriptions-item>
              <el-descriptions-item label="收货时间">{{ orderDetail.receiveTime }}</el-descriptions-item>
            </el-descriptions>
          </el-card>

          <!-- 商品清单 -->
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>商品清单</span>
              </div>
            </template>

            <el-table :data="orderDetail.items" border>
              <el-table-column label="商品信息" width="400">
                <template #default="{ row }">
                  <div class="goods-info">
                    <img :src="row.productPic" class="goods-image" />
                    <div class="goods-desc">
                      <p class="name">{{ row.productName }}</p>
                      <p class="attrs">{{ row.attrsText }}</p>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="单价" width="120" align="center">
                <template #default="{ row }">¥{{ row.productPrice?.toFixed(2) }}</template>
              </el-table-column>
              <el-table-column prop="productQuantity" label="数量" width="100" align="center" />
              <el-table-column label="小计" width="120" align="center">
                <template #default="{ row }">
                  ¥{{ (row.productPrice * row.productQuantity)?.toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <!-- 支付信息 -->
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>支付信息</span>
              </div>
            </template>

            <div class="payment-info">
              <div class="info-item">
                <span class="label">商品总额：</span>
                <span class="value">¥{{ orderDetail.totalMoney?.toFixed(2) }}</span>
              </div>
              <div class="info-item">
                <span class="label">运费：</span>
                <span class="value">+ ¥{{ orderDetail.postFee?.toFixed(2) }}</span>
              </div>
              <div class="info-item total">
                <span class="label">实付金额：</span>
                <span class="value">¥{{ orderDetail.payMoney?.toFixed(2) }}</span>
              </div>
            </div>
          </el-card>

          <!-- 物流信息 -->
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>物流信息</span>
              </div>
            </template>
            <div v-if="orderDetail.deliverInfo" class="logistics-info">
              <div class="company">物流公司：{{ orderDetail.deliverInfo.company }}</div>
              <div class="tracking-no">运单编号：{{ orderDetail.deliverInfo.trackingNo }}</div>
              <el-timeline>
                <el-timeline-item
                    v-for="(track, index) in orderDetail.deliverInfo.tracks"
                    :key="index"
                    :timestamp="track.time">
                  {{ track.info }}
                </el-timeline-item>
              </el-timeline>
            </div>
            <div v-else class="empty-logistics">暂无物流信息</div>
          </el-card>
        </div>
      </template>
    </el-skeleton>
  </div>
</template>

<style scoped lang="scss">
/* 保持原有样式不变，增加空物流提示样式 */
.empty-logistics {
  padding: 20px;
  color: #999;
  text-align: center;
}
</style>